'''
Created on Apr 27, 2012

@author: oabalbin
'''
import random
import sys

def write_random_records(fqa, fqb, N=1000):
    """ get N random headers from a fastq file without reading the
    whole thing into memory
    python get_subset.py /path/to/reads_1.fastq /path/to/reads_2.fastq 100
    """
    records = sum(1 for _ in open(fqa)) / 4
    print records
    #rand_records = sorted([random.randint(0, records - 1) for _ in xrange(N)])
    rand_records = sorted(random.sample(xrange(records), int(N)))
    fha, fhb = open(fqa),  open(fqb)
    suba, subb = open(fqa + ".subset", "w"), open(fqb + ".subset", "w")
    rec_no = 0
    for rr in rand_records:

        while rec_no < rr:
            rec_no += 1       
            for i in range(4): fha.readline()
            for i in range(4): fhb.readline()
        for i in range(4):
            suba.write(fha.readline())
            subb.write(fhb.readline())
        rec_no += 1

    print >>sys.stderr, "wrote to %s, %s" % (suba.name, subb.name)
    fha.close()
    fhb.close()
    suba.close()
    subb.close()
    

if __name__ == "__main__":
    N = 100 if len(sys.argv) < 4 else int(sys.argv[3])
    write_random_records(sys.argv[1], sys.argv[2], N)
    
'''
Take 4 fastq files
    2 tumor, 2 normal

Hardcode the proportions to mix
T N
90 10
80 20
70 30
60 40
50 50
40 50

Generate the random vector for reads
pick e.g 80 % of numbers, sort it, pick those reads from the tumor fastq
pick     20 % of numbers, sort it, pick those reads from the normal fastq

Write a single file with reads1, reads2.

'''